<!-- user-set -->
<template>
    <div class="set-wrapper">
        <el-table
        v-loading="loading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        :data="tableData"
        height="100%"
        border
        style="width: 100%">

            <el-table-column
            label="序号"
            type="index"
            width="100"
            align="center"
            >
            </el-table-column>

            <el-table-column
            label="用户名"
            prop="username"
            align="center"
            >
            </el-table-column>

            <el-table-column
            label="部门ID"
            prop="organizationid"
            align="center"
            >
            </el-table-column>

            <el-table-column
            label="人脸信息"
            align="center"
            >
                <template slot-scope="scope">
                    <span v-if="scope.row.faceFeature" style="color: green">已配置</span>
                    <span v-else style="color: #f40">未配置</span>
                </template>
            </el-table-column>

            <el-table-column
            label="操作"
            align="center"
            >
                <template slot-scope="scope">
                     <el-button 
                     type="text"
                     @click="handleCap(scope.row)">采集人脸</el-button>   
                </template>
            </el-table-column>

        </el-table>

        <!-- 对话框 -->
        <el-dialog 
        width="84%"
        :title="dialogTitle" 
        :close-on-click-modal="false"
        :visible.sync="dialogFormVisible">
           <div class="wrapper">
                <div class="left">
                    <!--图片展示-->
                    <video ref="video" autoplay></video>
                </div>
                <div class="right">
                   <!--canvas截取流-->
                    <canvas ref="canvas" width="400" height="400"></canvas>     
                </div>
           </div>  
           <!--确认-->
            <el-button type="primary" @click="photograph">点击拍照</el-button>   
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button :loading="submiting" type="primary" @click="handleLogInByFace">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {
    getUserList,
    uploadFace
} from '@/apis'
export default {
    name: 'user-set',
    components: {
        
    },
    watch: {
        dialogFormVisible (newVal, oldVal) {
            if (!newVal) {
                this.closeCamera();
            }
        }
    },
    data () {
        
        return {
            tableData: [],
            loading: false,
            dialogTitle: '采集人脸',
            dialogFormVisible: false,
            file: null,
            submiting: false,
            userId: null
        }
    },
    props: {},
    methods: {
        // 获取用户列表
        async getUserList () {
            try {
                // let id = 99;
                let id = window.localStorage.getItem('organizationId');
                this.loading = true;
                let res = await getUserList(id);
                console.log('获取用户列表', res);
                let {
                    code,
                    msg,
                    data
                } = res.data;
                if (code == 200) {
                    
                    this.tableData = data;
                    this.loading = false;
                    
                } else if (code == -2) {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    })
                    this.$store.commit('CLEAR_LOGIN');
                    this.$router.push('/login').catch({});  
                    this.loading = false;  
                } else {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    });
                    this.loading = false;
                }
            } catch(e) {
                this.loading = false;
                console.log('获取用户列表',e)
            }
        },

        // 点击探出采集人脸
        handleCap (row) {
            console.log('row', row);
            this.callCamera();
            this.userId = row.userId;
            this.dialogFormVisible = true;
        },

        // 调用摄像头
        callCamera() {
            // H5调用电脑摄像头API
            navigator.mediaDevices
                .getUserMedia({
                    video: true,
                })
                .then((success) => {
                    // 摄像头开启成功
                    this.$refs["video"].srcObject = success;
                    // 实时拍照效果
                    this.$refs["video"].play();
                })
                .catch((error) => {
                    console.log(error)
                    console.error("摄像头开启失败，请检查摄像头是否可用！");
                });
        },
        // 拍照
        photograph() {
            let ctx = this.$refs["canvas"].getContext("2d");
            // 把当前视频帧内容渲染到canvas上
            ctx.drawImage(this.$refs["video"], 0, 0, 400, 400);
            // 转base64格式、图片格式转换、图片质量压缩
            let imgBase64 = this.$refs["canvas"].toDataURL("image/jpeg", 0.7); // 由字节转换为KB 判断大小
            var blob = this.dataURLtoBlob(imgBase64);
            this.file = this.blobToFile(blob, Date.now());
            
        },
        // 关闭摄像头
        closeCamera() {
            if (!this.$refs["video"].srcObject) {
                this.dialogCamera = false;
                return;
            }
            let stream = this.$refs["video"].srcObject;
            let tracks = stream.getTracks();
            tracks.forEach((track) => {
                track.stop();
            });
            this.$refs["video"].srcObject = null;
            try {
                this.$nextTick(() => {
                    this.$refs["canvas"].getContext('2d').clearRect(0, 0, 670, 400)
                })
            } catch (e) {
                console.log('清除canvas', e);
            }
        },

        //将base64转换为blob
        dataURLtoBlob (dataurl) { 
            var arr = dataurl.split(','),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], { type: mime });
        },
        //将blob转换为file
        blobToFile (theBlob, fileName){
            theBlob.lastModifiedDate = new Date();
            theBlob.name = fileName;
            return theBlob;
        },

        // 调用接口传图片请求
        async handleLogInByFace () {
            try {
                this.submiting = true;
                let file = this.file;
                var formdata=new FormData();
                formdata.append("file", file);
                formdata.append("userId", this.userId);
                let res = await uploadFace(formdata);
                console.log('人脸请求', res);
                let {
                    code,
                    msg
                } = res.data;
                if (code == 200) {
                    this.closeCamera();
                    this.getUserList();
                    this.dialogFormVisible = false; 
                    this.submiting = false;
                    this.file = null;
                } else if (code == -2) {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    })
                    this.$store.commit('CLEAR_LOGIN');
                    this.$router.push('/login').catch({});  
                } else {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    })            
                    this.submiting = false;

                }
            } catch(e) {
                console.log('requestOutStore',e)
                this.submiting = false;
            }
        },


    },
    created () {
        this.getUserList();
    },
    beforeDestroy () {
        this.closeCamera();
    }
}
</script>
<style lang='scss'>
.cap-btn {
    font-size: 32px; 
    color: #fff;
    cursor: pointer;

    &:hover {
        color: rgba(255, 255, 255, 0.8)
    }
}

.wrapper {
    width: 100%;
    height: 400px;
    overflow: hidden;

    .left {
        width: 43%;
        float: left;
        height: 100%;

        video {
            width: 100%;
            height: 100%;
            object-fit: fill;
        }
    }

    .right {
        width: 43%;
        float: right;
        height: 100%;
        background: #f1f2f3;

        canvas {
           width: 100%!important;
           height: 400px; 
        }
    }
}

</style>